<?php

namespace app\api\controller;

use addons\epay\library\Service;
use addons\epay\library\Yansongda\Pay\Pay as Yansongda;
use app\common\controller\Api;
use app\common\model\SubOrder;
use app\common\model\User;
use Exception;
use think\facade\Db;

class Pay extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';

    public function pay(){
        $user=$this->auth->getUser();

        $sub_order_id=request()->param('sub_order_id')?:0;

        $SO=new SubOrder();
        if(!$user['wx_miniapp_openid'])
            $this->error('账号缺少小程序openid');
        $sub_order=$SO::get($sub_order_id);

        if(!$sub_order){
            $this->error('未找到订单信息');
        }
        if($sub_order['pay_status']!=0){
            $this->error('订单已经不是待支付状态');
        }
        if($sub_order['user_id']!=$user['id']){
            $this->error('只可以支付自己的订单');
        }

        //回调链接
        $notifyurl = $this->request->root(true) . '/pay/notify/out_trade_no/' . $sub_order['order_sn'];
        $returnurl = $this->request->root(true) . '/pay/notify/out_trade_no/' . $sub_order['order_sn'];
        $response  = Service::submitOrder(
            $sub_order['pay_price'],
            $sub_order['order_sn'],
            'wechat',
            '支付订单',
            $notifyurl,
            $returnurl,
            'miniapp',
            $user['wx_miniapp_openid']
        );
        adlog('支付参数',$response);

        $sub_order->save();

        $this->success('获取支付参数成功',['response' => json_decode($response)]);
    }

    public function notify(){
        adlog('支付回调原本',file_get_contents("php://input"));
        $pay     = Service::checkNotify('wechat');
        if (!$pay) {
            echo '验签失败';
            return 'failed';
        }
        $data = $pay->verify();
        adlog('支付回调',$data);
        Db::startTrans();
        try {
            $out_trade_no = $data['out_trade_no'];
            $order        = SubOrder::get(['order_sn' => $out_trade_no,'pay_status' =>0]);
            if ($order) {
                $order['pay_status']   = 1;
                $order['pay_time'] = time();
                $order->save();
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            adlog('支付错误信息',$e->getMessage());
            exit;
        }
        return 'success';
    }

    public static function refund($order,$desc,$money=0){
        //$order=Order::get(['order_id'=>$order_id]);
        if($order['refund_time']!=null){
            return false;
        }

        $config=Service::getConfig('wechat');
        $pay=Yansongda::wechat($config);
        $refund_order = [
            'out_trade_no'  => $order['order_sn'],
            'out_refund_no' => 'R'.$order['order_sn'].'-'.time(),
            'total_fee'     => $order['pay_price'] * 100,
            'refund_fee'    => $money?$money*100:$order['pay_price'] * 100,
            'refund_desc'   => $desc,
            'type'          => 'miniapp'
        ];

        $refund = $pay->refund($refund_order);
        $refund = json_decode($refund, true);

        adlog('退款', $refund);
        if ($refund && ((isset($refund['return_code']) && $refund['return_code'] == 'SUCCESS')||(isset($refund['msg']) && $refund['msg'] == 'Success'))) {
            return true;
        }
        return false;
    }

}